<?php

namespace app\index\controller;

use app\common\controller\Home;
use app\common\model\Users;
use think\Cache;

class Charging extends Home {

    public function index($id)
    {
        $config = $this->get_config();
        $view_info = base64_decrypt($id, config('view_key'));
        $view_info = json_decode($view_info, true);
        if (!isset($view_info['view_id']) || $view_info['view_id'] == 0) {
            die();
        }
        $model = model('ViewLogs');
        $info = $model->lock(true)->where('view_id', $view_info['view_id'])->find();
        if ($info['status'] != 0) {
            die('已计费');
        }
        $model->save(['status' => 1], ['view_id' => $info['view_id']]);
        $counts_res = $this->check_counts($config, $info);
        if ($counts_res === false) {
            $model->save(['status' => 2], ['view_id' => $info['view_id']]);
        } else {
            $user_model = new Users();
            $user_model->share_calculate($counts_res, $config, $info);
        }
    }

    public function get_config()
    {
        $config = unserialize(Cache::store('redis')->get(config('system_config_name')));
        if (!$config) {
            $res = model('Options')->select();
            $config = [];
            foreach ($res as $v) {
                $config[$v['name']] = $v['value'];
            }
            Cache::store("redis")->set(config('system_config_name'), serialize($config));
        }
        return $config;
    }

    private function check_counts($config, $share_info)
    {
        $money_counts = $config['money_counts'];
        $reduce_number = $config['reduce_number'];
        $able_counts = intval($money_counts * (1 - $reduce_number/100));
        $counts = model('ViewLogs')->where(['share_id' => $share_info['share_id'], 'status' => 1])->count();
        if ($counts < $able_counts) {
            return $counts;
        } else {
            return false;
        }
    }


}
